import React, { useState, useEffect, useRef } from 'react';
import './WaterFillCircle.css';

const WaterFillCircle = ({ percentage = 50, duration = 2000, waveColor }) => {
  const [progress, setProgress] = useState(0);
  const waveRef = useRef(null);
  const animationRef = useRef(null);
  const frameRef = useRef(0);
  const [displayNumber, setDisplayNumber] = useState(0);

  // 处理填充动画
  useEffect(() => {
    let start = null;
    const increment =  20 ; //percentage / (duration / 18); // 每帧增量
    
    const animateFill = (timestamp) => {
      if (!start) start = timestamp;
      const elapsed = timestamp - start;
      const fillProgress = Math.min(elapsed / duration * percentage, percentage);
      
      setProgress(fillProgress);
      setDisplayNumber(prev => {
        const newValue = prev + increment;
        return newValue < duration ? newValue : duration;
      });
      if (fillProgress < percentage) {
        animationRef.current = requestAnimationFrame(animateFill);
      }
    };

    animationRef.current = requestAnimationFrame(animateFill);
    
    return () => {
      cancelAnimationFrame(animationRef.current);
    };
  }, [percentage, duration]);

  // 处理波浪动画
  useEffect(() => {
    const animateWave = () => {
      frameRef.current += 0.05;
      if (waveRef.current) {
        const wavePath = calculateWavePath(frameRef.current);
        waveRef.current.setAttribute('d', wavePath);
      }
      requestAnimationFrame(animateWave);
    };
    
    const animationId = requestAnimationFrame(animateWave);
    
    return () => {
      cancelAnimationFrame(animationId);
    };
  }, []);

  // 计算波浪路径
  const calculateWavePath = (frame) => {
    const waveHeight = 10;
    const waveWidth = 100;
    const segments = 20;
    let path = `M 0 ${waveHeight}`;
    
    for (let i = 1; i <= segments; i++) {
      const x = (i / segments) * waveWidth;
      const y = waveHeight * Math.sin((i / segments) * Math.PI * 2 + frame * 2);
      path += ` L ${x} ${y}`;
    }
    
    path += ` L ${waveWidth} ${waveHeight} L ${waveWidth} 100 L 0 100 Z`;
    return path;
  };
  // const getWaterColor = (progress) => {
  //   // 从浅蓝 (#4facfe) 到深蓝 (#00a1ff) 的渐变
  //   const hueStart = 126; // 浅蓝色相
  //   const hueEnd = 126;   // 深蓝色相
  //   const saturation = 60; // 饱和度固定
  //   const lightness = 80 - (progress / 100) * 30; // 亮度随水位降低
    
  //   return `hsl(${hueStart + (hueEnd - hueStart) * (progress / 100)}, ${saturation}%, ${lightness}%)`;
  // };

  // 计算波浪颜色（更深一些）
  const getWaveColor = (progress) => {
    return `hsl(171, 90%, ${50 - (progress / 100) * 10}%)`;
  };
  // 计算水的位置和颜色
  const waterPosition = 100 - progress;
  const waterColor = getWaveColor(progress)//`hsl(171, 100%, 50%)`;
  // const waveColor = getWaterColor(progress)//`hsl(126, 61.60%, 42.90%)`;
  // const waveColor1 = getWaterColor(progress); //`hsl(126, 61.60%, 42.90%)`;

  return (
    <div className="water-container">
        <div className='speedBg'></div>
      <svg 
        viewBox="0 0 100 100" 
        className="water-circle"
      >
        <defs>
          <linearGradient id="cssVarGrad" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="var(--gradient-start)" />
            <stop offset="100%" stopColor="var(--gradient-end)" />
          </linearGradient>
        </defs>
        {/* 背景圆 */}
        <circle 
          cx="50" 
          cy="50" 
          r="45" 
          fill="none" 
        //   stroke="#e0e0e0" 
        //   strokeWidth="2"
        />
        
        {/* 裁剪路径 */}
        <clipPath id="water-clip">
          <circle cx="50" cy="50" r="45" />
        </clipPath>
        
        <g clipPath="url(#water-clip)">
          {/* 水填充 */}
          <rect 
            x="0" 
            y={waterPosition} 
            width="100" 
            height="100" 
            fill={waterColor} 
            opacity="0"
          />
          
          {/* 波浪层1 */}
          <path
            ref={waveRef}
            fill={waveColor}
            opacity="0.7"
            transform={`translate(0, ${waterPosition - 10})`}
          />
          
          {/* 波浪层2 (延迟动画) */}
          <path
            d={calculateWavePath(frameRef.current - 0.5)}
            fill={waveColor}
            opacity="0.4"
            transform={`translate(0, ${waterPosition - 8})`}
          />
        </g>
        
        {/* 百分比文字 */}
        <text 
          x="50" 
          y="50" 
          textAnchor="middle" 
          dominantBaseline="middle" 
          fill="#fff"
          fontSize="20"
          fontWeight="bold"
        >
          {/* {duration / 10000}s */}
          {(displayNumber / 10000).toFixed(2)}s
        </text>
      </svg>
    </div>
  );
};

export default WaterFillCircle;